package com.kylin;

import com.alibaba.fastjson.JSONObject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wuxianwen on 2018/4/18.
 */
@RestController
//@RequestMapping("/")
public class Dxf2JsonController {
    private static Connection conn = null;
    private static PreparedStatement ps = null;
    private static ResultSet rs = null;
    private static ResultSetMetaData m = null;

    @RequestMapping("/dxf")
    public String testJson() throws ClassNotFoundException, SQLException {
        List<DxfModel> populate = null;
        conn = DBConn.conn();//调用 DBconnection 类的 conn() 方法连接数据库
        String sql = "select * from cad";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            populate = Populate(rs, DxfModel.class);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBConn.close();
        }
        JSONObject jObject2 = new JSONObject();
        jObject2.put("dxfList", populate);
        String json3 = jObject2.toJSONString();
        return json3;
    }

    public static List Populate(ResultSet rs, Class cc) throws SQLException, InstantiationException, IllegalAccessException {
        //结果集 中列的名称和类型的信息
        ResultSetMetaData rsm = rs.getMetaData();
        int colNumber = rsm.getColumnCount();
        List list = new ArrayList();
        Field[] fields = cc.getDeclaredFields();
        //遍历每条记录
        while (rs.next()) {
            //实例化对象
            Object obj = cc.newInstance();
            //取出每一个字段进行赋值
            for (int i = 1; i <= colNumber; i++) {
                Object value = rs.getObject(i);
                //匹配实体类中对应的属性
                for (int j = 0; j < fields.length; j++) {
                    Field f = fields[j];
                    if (f.getName().equals(rsm.getColumnName(i))) {
                        boolean flag = f.isAccessible();
                        f.setAccessible(true);
                        f.set(obj, value);
                        f.setAccessible(flag);
                        break;
                    }
                }
            }
            list.add(obj);
        }
        return list;
    }
}
